package cn.codeforfun.initialization.common;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wangbin
 */
@RestController
@Slf4j
public class CommonController {

    @Resource
    private CommonService commonService;

    private static final String SHOW_DATABASES_SQL = "show databases";
    private static final String[] MYSQL_SYSTEM_TABLE = {"information_schema", "mysql", "performance_schema"};

    @GetMapping("/getDashboardInformation")
    public List<DashboardInformation> getDashboardInformation() {
        return commonService.getDashboardInformation();
    }

    /**
     * todo
     */
    @GetMapping("/listAllTables")
    public List<String> listAllTables() throws SQLException {
        String jdbcUrl = "jdbc:mysql://localhost:3306";
        String username = "root";
        String password = "root";
        String driverClass = "com.mysql.cj.jdbc.Driver";
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(jdbcUrl);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClass);
        QueryRunner qr = new QueryRunner(dataSource);
        ResultSetHandler<List<String>> rsh = new ColumnListHandler<>();
        List<String> resultList = qr.query(SHOW_DATABASES_SQL, rsh);
        return resultList.stream()
                .filter(s -> !Arrays.asList(MYSQL_SYSTEM_TABLE).contains(s))
                .collect(Collectors.toList());
    }

    /**
     * 初始化数据库
     * todo
     */
    @GetMapping("/initialDatabase")
    public boolean initialDatabase() {
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
        log.info("format:{}", format);
        return false;
    }


}
